#!/bin/bash
set -e

# 定义可配置的参数
DOCKER_PORT=44888  # 远程访问端口

echo "===== 开始安装必要工具 ====="
sudo yum install  -y yum-utils device-mapper-persistent-data lvm2

echo "===== 添加阿里云Docker源 ====="
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

echo "===== 安装Docker ====="
sudo yum install -y docker-ce docker-ce-cli containerd.io

echo "===== 启动Docker服务并设置开机自启 ====="
sudo systemctl start docker
sudo systemctl enable docker

echo "===== 验证Docker版本 ====="
docker -v || sudo docker -v  # 兼容不同环境下的权限配置

echo "===== 配置Docker镜像加速 ====="
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": [
        "https://docker.registry.cyou/",
        "https://docker-cf.registry.cyou/",
        "https://dockercf.jsdelivr.fyi/",
        "https://docker.jsdelivr.fyi/",
        "https://dockertest.jsdelivr.fyi/",
        "https://mirror.aliyuncs.com/",
        "https://dockerproxy.com/",
        "https://mirror.baidubce.com/",
        "https://docker.m.daocloud.io/",
        "https://docker.nju.edu.cn/",
        "https://docker.mirrors.sjtug.sjtu.edu.cn/",
        "https://docker.mirrors.ustc.edu.cn/",
        "https://mirror.iscas.ac.cn/",
        "https://docker.rainbond.cc/",
        "https://jq794zz5.mirror.aliyuncs.com",
        "https://66a84trh.mirror.aliyuncs.com"]
}
EOF

echo "===== 备份并修改配置文件（使用端口: $DOCKER_PORT） ====="
# 备份原始配置
sudo cp /lib/systemd/system/docker.service /lib/systemd/system/docker.service.bak

# 使用变量修改配置文件，设置远程访问端口
sudo sed -i "s#ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock#ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock -H tcp://0.0.0.0:${DOCKER_PORT} -H unix:///var/run/docker.sock#g" /lib/systemd/system/docker.service

echo "===== 重新加载配置并重启Docker ====="
sudo systemctl daemon-reload
sudo systemctl restart docker

echo "===== 检查服务状态 ====="
if sudo systemctl is-active --quiet docker; then
    echo "Docker服务运行正常"
else
    echo "错误：Docker服务未正常启动" >&2
    exit 1
fi

echo "===== 验证镜像加速配置 ====="
# 忽略大小写匹配，同时显示实际配置的镜像源
if docker info | grep -qi "registry mirrors"; then
    echo "镜像加速配置已生效"
    # 显式输出镜像源列表（兼容不同格式）
    docker info | grep -A 20 -i "registry mirrors"
else
    echo "警告：镜像加速配置未生效" >&2
fi

echo "===== 测试访问 ====="
echo "本地测试结果："
curl -s http://localhost:${DOCKER_PORT}/version

echo "====================================="
echo "Docker 安装配置完成！远程访问端口：${DOCKER_PORT}"
echo "====================================="
